package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;
    @Override
    public PageResult pageList(RequestParams param) {
        //创建请求参数
        SearchRequest request=new SearchRequest("hotel");
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //封装请求参数
        if(StringUtils.isBlank(param.getKey())){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else{
            boolQuery.must(QueryBuilders.matchQuery("all",param.getKey()));
        }
        //添加精准过滤条件，品牌
        if(StringUtils.isNotBlank(param.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand",param.getBrand()));
        }
        //添加精准过滤条件，city
        if(StringUtils.isNotBlank(param.getCity())){
            boolQuery.filter(QueryBuilders.termQuery("city",param.getCity()));
        }
        //添加精准过滤条件，品牌
        if(StringUtils.isNotBlank(param.getStarName())){
            boolQuery.filter(QueryBuilders.termQuery("starName",param.getStarName()));
        }
        if(param.getMaxPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(param.getMaxPrice()));
        }
        if(param.getMinPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(param.getMinPrice()));
        }
        //算分查询
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(boolQuery, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD", true), //算分查询条件
                        ScoreFunctionBuilders.weightFactorFunction(10)) //权重

        });
        functionScoreQueryBuilder.boostMode(CombineFunction.SUM);
        if("score".equals(param.getSortBy())){
            request.source().sort("score",SortOrder.DESC);
        }
        if("price".equals(param.getSortBy())){
            request.source().sort("price",SortOrder.ASC);
        }
        request.source().highlighter(new HighlightBuilder().field("name").preTags("<em>").postTags("</em>").requireFieldMatch(false));
        // 放入source
        request.source().query(functionScoreQueryBuilder);
        int page = param.getPage();
        int size = param.getSize();
        //分页
        request.source().from((page - 1) * size).size(size);
        //我附近的酒店
        if(StringUtils.isNotBlank(param.getLocation())){
            request.source().sort(SortBuilders.geoDistanceSort("location",new GeoPoint(param.getLocation())
                    ).order(SortOrder.ASC)
                            .unit(DistanceUnit.KILOMETERS)
                    );

        }
        //发送请求
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            SearchHits hits = response.getHits();
            long total = hits.getTotalHits().value;
            SearchHit[] hitsHits = hits.getHits();
            List<HotelDoc> hotels=new ArrayList<>();
            if(hitsHits!=null &&hitsHits.length>0){
                for (SearchHit hitsHit : hitsHits) {
                    String source = hitsHit.getSourceAsString();
                    HotelDoc hotelDoc = JSON.parseObject(source, HotelDoc.class);
                    Object[] sortValues = hitsHit.getSortValues();
                    if(sortValues!=null &&sortValues.length>0){
                        Object distance = sortValues[0];
                        hotelDoc.setDistance(distance);
                    }
                    Map<String, HighlightField> highlightFields = hitsHit.getHighlightFields();
                    if(highlightFields!=null &&highlightFields.size()>0){
                        HighlightField field = highlightFields.get("name");
                        if (field != null) {
                            // 获取高亮值
                            String name = field.getFragments()[0].string();
                            hotelDoc.setName(name);
                        }
                    }
                    hotels.add(hotelDoc);
                }
            }
            return PageResult.of(total,hotels);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams param) {
        //创建请求参数
        SearchRequest request=new SearchRequest("hotel");
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //封装请求参数
        if(StringUtils.isBlank(param.getKey())){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else{
            boolQuery.must(QueryBuilders.matchQuery("all",param.getKey()));
        }
        //添加精准过滤条件，品牌
        if(StringUtils.isNotBlank(param.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand",param.getBrand()));
        }
        //添加精准过滤条件，city
        if(StringUtils.isNotBlank(param.getCity())){
            boolQuery.filter(QueryBuilders.termQuery("city",param.getCity()));
        }
        //添加精准过滤条件，品牌
        if(StringUtils.isNotBlank(param.getStarName())){
            boolQuery.filter(QueryBuilders.termQuery("starName",param.getStarName()));
        }
        if(param.getMaxPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(param.getMaxPrice()));
        }
        if(param.getMinPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(param.getMinPrice()));
        }
        if("score".equals(param.getSortBy())){
            request.source().sort("score",SortOrder.DESC);
        }
        if("price".equals(param.getSortBy())){
            request.source().sort("price",SortOrder.ASC);
        }
        request.source().query(boolQuery);
        int page = param.getPage();
        int size = param.getSize();
        //分页
        request.source().from((page - 1) * size).size(size);
        //聚合结果显示的条数
        request.source().size(0);
        request.source().aggregation(AggregationBuilders.terms("brandagg").field("brand"));
        request.source().aggregation(AggregationBuilders.terms("cityagg").field("city"));
        request.source().aggregation(AggregationBuilders.terms("starNameagg").field("starName"));
        Map<String, List<String>> map = new HashMap<>();
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            List<String> brand = aggress(response, "brand");
            List<String> city = aggress(response, "city");
            List<String> starName = aggress(response, "starName");
            map.put("city", city);
            map.put("starName", starName);
            map.put("brand", brand);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return map;
    }
  public List<String> aggress(SearchResponse response,String field){
       List<String> list = new ArrayList<>();
        //设置聚合结果名称和聚合字段
          Aggregations aggregations = response.getAggregations();
          Terms aggregation = aggregations.get(field + "agg");
          List<? extends Terms.Bucket> buckets = aggregation.getBuckets();
          if(buckets!=null &&buckets.size()>0){
              for (Terms.Bucket bucket : buckets) {
                  String key = bucket.getKeyAsString();
                  list.add(key);
              }
          }
    return list;
  }
}
